<?php

namespace backend\helpers;

use backend\models\match\Match;
use backend\models\match\MatchUser;
use common\components\RabbitMQ;
use PhpAmqpLib\Message\AMQPMessage;
use common\helpers\GlobalConfig;
use Yii;
use yii\helpers\ArrayHelper;


/**
 * Class MatchHelper
 * @package backend\helpers
 */
class MatchHelper
{
    public static $operators = null;

    /**
     * 格式化赛事状态
     */
    public static function formatStatus(Match $model)
    {
        if ($model->status == 1) {
            return '进行中';
        } elseif ($model->status == 2) {
            $data = '已结束';
            if ($model->status2 == 1) {
                $data .= "(终止)";
            }
            return $data;
        } elseif ($model->status == 0) {
            return '未开始';
        } else {
            return '待发布';
        }

    }

    /**
     * 格式化当前流转状态
     */
    public static function formatStatus2(Match $model)
    {
        if ($model->status == 1) {
            return '请上传比赛结果';
        } elseif ($model->status == 2) {
            return '';
        } elseif ($model->status == 0) {
            if ($model->status2 == 0) {
                return '已保存';
            } elseif ($model->status2 == 1) {
                $value = '报名中';
                if ($model->status2_flag == 10) {
                    $value .= "(邀请)";
                } else {
                    $value .= "(开放)";
                }
                return $value;
            } elseif ($model->status2 == 2) {
                return '请制定赛程安排';
            } elseif ($model->status2 == 3) {
                return '报名已满';
            } else {
                return '';
            }
        } else {
            return '';
        }

    }

    /**
     * 格式化赛事状态
     */
    public static function matchStatus($status=0)
    {
        if ($status == 1) {
            return '进行中';
        } elseif ($status == 2) {
            return '已结束';
        } elseif ($status == 0) {
            return '未开始';
        } else {
            return '已删除';
        }
    }

    /**
     * 获取赛事创建人
     */
    public static function getCreator(Match $model) {
        if ($model->user_id) {
            return '@todo';
        } elseif ($model->operator_id) {
            $data = Yii::$app->db->createCommand("select username from admin where id=:id", [':id'=>$model->operator_id])->queryScalar();
            return $data ? $data : '';
        }
        return ' - ';
    }

    /**
     * 获取管理员
     */
    public static function getOperator($id) {

        if (static::$operators === null) {
            $operators= Yii::$app->db->createCommand("select id,username from admin", [])->queryAll();
            static::$operators = ArrayHelper::index($operators, 'id');
        }

        return isset(static::$operators[$id]['username']) ? static::$operators[$id]['username'] : '';
    }

    /**
     * 获取赛事创建人
     */
    public static function getRanking($matchId, $ranking=1) {
        if ($ranking == 1) {
            return '冠军';
        } else {
            $value = Yii::$app->db->createCommand("select name from match_prize_config where match_id=:match_id and ranking=:ranking", [':match_id' => $matchId, ':ranking' => $ranking])->queryScalar();
            return $value !== false ? $value : null;
        }
    }

    /**
     * 字符串截取
     *
     * @param $string
     * @param $length
     * @param string $etc
     * @return string
     */
    public static function truncate($string, $length, $etc = '...')
    {
        $result = '';
        $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
        $strlen = strlen($string);
        for ($i = 0; (($i < $strlen) && ($length > 0)); $i++)
        {
            if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0'))
            {
                if ($length < 1.0)
                {
                    break;
                }
                $result .= substr($string, $i, $number);
                $length -= 1.0;
                $i += $number - 1;
            }
            else
            {
                $result .= substr($string, $i, 1);
                $length -= 0.5;
            }
        }
        $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
        if ($i < $strlen)
        {
            $result .= $etc;
        }
        return $result;
    }

    /**
     * 获取文件路径
     *
     * @param yii\web\UploadedFile $uploadfile
     * @param string $category
     * @return string
     */
    public static function getFilePath($uploadfile, $category='', $absolutely=false) {
        if ($absolutely) {
            $dirname = $category;
        } else {
            $dirname = 'uploads/';
            if (!empty($category)) {
                $category = trim($category, '/');
                $dirname .= "$category/";
            }
        }
        @mkdir($dirname, 0777, true);

        $filename = $uploadfile->baseName . '.' . $uploadfile->extension;
        $iteration = 0;
        while (file_exists($dirname.$filename)) {
            $iteration ++;
            $filename = $uploadfile->baseName . '-'.$iteration . '.' . $uploadfile->extension;
        }

        return $dirname.$filename;
    }

    /**
     * 数组键值拼接
     * @param $data
     * @param string $prefix
     * @return string
     */
    public static function buildString($data, $prefix = '&') {
        return implode($prefix, array_map(function ($k, $v) {
            return "{$k}={$v}";
        }, array_keys($data), $data));
    }

    /**
     * 根据userId获取收货地址
     */
    public static function getUserAddress($userId) {
        return Yii::$app->db->createCommand("select * from user_address where user_guid=:user_id", [':user_id'=>$userId])->queryOne();
    }

    /**
     * 获取分享账号ID
     * @param $matchId
     * @return string
     */
    public static function getShareAccountId($matchId) {
        return $matchId.'_0000';
    }

    /**
     * 优化观看人数
     * @param $passedTime
     * @param $num
     * @param bool $isEnding
     * @param int $displayCount
     * @param int $realCount
     * @return array
     */
    public static function getDisplayCount($matchId, $passedTime, $realCount=0, $incr=0) {
        //运营配置项
        $cfg_time= Yii::$app->params['viewer2:cfg_time']*60;
        $cfg_rate= Yii::$app->params['viewer2:cfg_rate'];
        $cfg_base= Yii::$app->params['viewer2:cfg_base'];

        $key = 'match_viewer2_'.$matchId;
        $isEnding = Yii::$app->redis->executeCommand('HGET', [$key, 'is_ending']);
        $displayCount = Yii::$app->redis->executeCommand('HGET', [$key, 'display_count']);
        if (!$isEnding) {
            $isEnding = 0;
        }
        if (!$displayCount) {
            $displayCount = 0;
        }

        $realCount += $incr;
        if ($realCount < 0) {
            $realCount = 0;
        }
        $game_cfg_base = $cfg_base * rand(8000,12000)/10000.0;
        $game_cfg_time = $cfg_time;
        $game_cfg_rate = $cfg_rate;

        // 优化显示人数
        if($isEnding){
            $displayCount += $incr;
        } else {
            if($passedTime < $game_cfg_time) {
                if ($incr <= 0) {
                    $displayCount = $displayCount + $incr;
                } else {
                    $displayCount = $displayCount + $game_cfg_rate * $incr;
                }
                if ($displayCount >= $game_cfg_base) {
                    $isEnding = 1;
                }
            } elseif ($passedTime >= $game_cfg_time && $passedTime < 2*$game_cfg_time) {
                if ($displayCount >= $game_cfg_base) {
                    $displayCount += $incr;
                    $isEnding = 1;
                } else {
                    $incr = ($game_cfg_base - $displayCount)/(2*$game_cfg_time - $passedTime);
                    $displayCount += intval($incr) + mt_rand(0, 10);
                }
            } else {
                $isEnding = 1;
                if ($displayCount < $game_cfg_base) {
                    $displayCount = $game_cfg_base + mt_rand(-10, 10);
                } else {
                    $displayCount += $incr;
                }
            }
        }
        if ($displayCount < 0) {
            $displayCount = 0;
        }

        // 保存新数据
        $isEnding = intval($isEnding);
        $displayCount = intval($displayCount);
        Yii::$app->redis->executeCommand('HSET', [$key, 'is_ending', $isEnding]);
        Yii::$app->redis->executeCommand('HSET', [$key, 'display_count', $displayCount]);

        return $displayCount;
    }


    /**
     * 获取赛事分值
     *      评分因素：人工置入,赛事大小状态,观看人数,预约人数,参赛队伍数,赛事开始时间
     * @param $data
     * @param string $max
     * @return float|int
     */
    public static function getScore($data, $extra=[]) {
        $timeMax = strtotime('10 years');
        $base = GlobalConfig::MATCH_SORT_BASE;

        if ($data['status'] == 1) {
            // 进行中：观看人数最多的排前边，如果观看人数相同，则比赛时间最近的在最前边
            $liveUrl = '';
            if (isset($data['extra']) && !empty($data['extra'])) {
                $extra = json_decode($data['extra'], 1);
                $liveUrl = isset($extra['live']) ? $extra['live'] : '';
            }

            if (($data['live_flag'] == 1 && !empty($liveUrl)) || ($data['source'] == 'other') && !empty($liveUrl)) {
                $viewer2 = Yii::$app->redis->executeCommand('HGET', ['match_viewer2_'.$data['id'], 'display_count']);
                $viewer2 = intval($viewer2);
                $score = 9*$base;
            } else {
                $viewer2 = 0;
                $score = 8*$base;
            }
            $score += $viewer2;
            $score += ($timeMax - strtotime($data['start_time']))/$timeMax;
        } elseif ($data['status'] == 0 && in_array($data['status2'], [2,3])) {
            // 预约观赛：预约人数最多的排前边，如果预约人数相同，则比赛时间最近的在最前边
            // $viewer = Yii::$app->db->createCommand("select num from match_viewer where match_id=:match_id;", [':match_id'=>$data['id']])->queryScalar();
            $viewer = 0;

            $score = 7*$base;
            $score += $viewer;
            $score += ($timeMax - strtotime($data['start_time']))/$timeMax;
        } elseif ($data['status'] == 0 && $data['status2'] == 1) {
            // 报名中：报名队伍数最多的排前边，如果报名战队数相同，则比赛时间最近的在最前边
            // $teamNum = MatchUser::teamNum($data['id']);
            $teamNum = 0;

            $score = 6*$base;
            $score += $teamNum;
            $score += ($timeMax - strtotime($data['start_time']))/$timeMax;
        } elseif ($data['status'] == 0 && $data['status2'] == 0) {
            // 未开始：比赛时间最近(最大)的在最前边

            $score = 5*$base;
            $score += ($timeMax - strtotime($data['start_time']))/$timeMax;
        } elseif ($data['status'] == 2) {
            // 比赛结束：按照结束时间排序，最后结束的排前边
            $score = 4*$base;
            $score += strtotime($data['end_time'])/1000000;
        } else {
            $score = 0;
        }

        return $score;
    }

    /**
     * 异步发消息
     * @param $groupId
     * @param $msg
     * @return array
     */
    public static function sendGroupMsg($groupId, $msg) {
        // 发消息
        try {
            $connection = RabbitMQ::getConnection();

            $channel = $connection->channel();
            $channel->queue_declare('im_group_msg', false, true, false, false, true);
            $msg = new AMQPMessage(json_encode(['group_id' => $groupId, 'msg' => $msg]),
                array('delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT)
            );
            $channel->basic_publish($msg, '', 'im_group_msg');

            // $channel->close();
            // $connection->close();
        } catch (\Exception $exception) {
            return ['code'=>0, 'msg'=>$exception->getMessage()];
        }

        return ['code'=>1];
    }
}






